package my.edu.model.User.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.websocket.server.PathParam;
import my.edu.common.domain.PageDTO;
import my.edu.common.exception.AdminException;
import my.edu.common.validate.groups.Insert;
import my.edu.common.domain.Response;
import my.edu.model.User.entity.Permission;
import my.edu.model.User.entity.Role;
import my.edu.model.User.entity.User;
import my.edu.model.User.entity.VO.PermissionTree;
import my.edu.model.User.entity.dto.RoleDTO;
import my.edu.model.User.service.IPermissionService;
import my.edu.model.User.service.IRoleService;
import my.edu.utils.PinyinUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/user/role")
@Tag(name = "角色接口")
public class RoleController {
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IPermissionService permissionService;


    @GetMapping("/list")
    @Operation(summary = "查询所有角色和权限")
    @RequiresPermissions(value = {"system:user"})
    public Response list(@ModelAttribute @Validated PageDTO page, String description,String name) {
        return Response.success(roleService.listVO(page,description,name));
    }

    @GetMapping
    @Operation(summary = "查询所有角色")
    @RequiresPermissions(value = {"system:user"})
    public Response onlylist() {
        return Response.success(roleService.list());
    }

    @GetMapping("/one")
    @Operation(summary = "根据id查询角色")
    @RequiresPermissions(value = {"system:user"})
    public Response list(@RequestParam Long id) {
        return Response.success(roleService.getVOone(id));
    }

    @PostMapping()
    @Operation(summary = "更新角色权限")
    @RequiresPermissions(value = {"system:user"})
    public Response update(@RequestBody @Validated RoleDTO roleDTO) {
        roleService.updateByDTO(roleDTO);
        return Response.success();
    }

    @PutMapping()
    @Operation(summary = "新增角色")
    @RequiresPermissions(value = {"system:user"})
    public Response save(@RequestBody @Validated(value = Insert.class) RoleDTO roleDTO) {
        roleService.saveNew(roleDTO);
        return Response.success();
    }

    @DeleteMapping()
    @Operation(summary = "删除角色")
    @RequiresPermissions(value = {"system:user"})
    public Response remove(Long id) {
        Role byId = roleService.getById(id);
        if (byId.getName().equals("admin"))throw new AdminException("超级管理员不能删除");
        roleService.removeRole(id);
        return Response.success();
    }

    @GetMapping("/permission")
    @Operation(summary = "查询所有权限")
    @RequiresPermissions(value = {"system:user"})
    public Response getPermission() {
        List<Permission> list = permissionService.list();
        Map<String, List<Permission>> collect = list.stream().collect(Collectors.groupingBy(
                Permission::getName,
                Collectors.mapping(
                        Function.identity(),
                        Collectors.toList()
                )
        ));
        return Response.success(collect);
    }

    @GetMapping("/permissionTree")
    @Operation(summary = "查询所有权限为树")
    @RequiresPermissions(value = {"system:user"})
    public Response getPermissionTree() {
        List<Permission> list = permissionService.list();
        Map<String, List<Permission>> collect = list.stream().collect(Collectors.groupingBy(
                Permission::getName,
                Collectors.mapping(
                        Function.identity(),
                        Collectors.toList()
                )
        ));
        List<PermissionTree> res = collect.entrySet().stream()
                .map(i -> {
                    PermissionTree permissionTree = new PermissionTree();
                    permissionTree.setTitle(i.getKey());
                    permissionTree.setValue(i.getKey());
                    permissionTree.setKey(i.getKey());
                    permissionTree.setChildren(i.getValue().stream().map(j -> {
                        PermissionTree permissionChild = new PermissionTree();
                        permissionChild.setId(j.getId());
                        permissionChild.setValue(j.getId()+"");
                        permissionChild.setKey(j.getId()+"");
                        permissionChild.setTitle(j.getDescription());
                        return permissionChild;
                    }).toList());
                    return permissionTree;
                })
                .sorted(Comparator.comparing(pt -> PinyinUtil.toPinyin(pt.getTitle()))) // 根据拼音排序
                .toList();

        return Response.success(res);
    }
}